package com.zunipe.trainticketsystem.database.handler;

import com.zunipe.trainticketsystem.TrainTicketApplication;
import com.zunipe.trainticketsystem.database.Result;
import com.zunipe.trainticketsystem.database.dao.TrainDao;
import com.zunipe.trainticketsystem.database.entity.Train;

import java.util.List;

public class TrainHandler {

    private final TrainDao trainDao;

    public TrainHandler() {
        trainDao = TrainTicketApplication.getInstance().getTrainDao();
    }

    public List<Train> getTrainListByTrainNumber(String trainNumber) {
        return trainDao.findByTrainNumber(trainNumber);
    }

    public List<Train> getTrainList() {
        return trainDao.findAll();
    }

    public Train getByTrainNumberAndType(String trainNumber, String type) {
        return trainDao.findByTrainNumberAndType(trainNumber, type);
    }

    public Train getTrainById(int id) {
        return trainDao.findById(id);
    }

    public Result buyTicket(Train targetTrain) {
        synchronized (this) {
            Train queryTrain = trainDao.findById(targetTrain.getId());
            if (queryTrain == null || queryTrain.getCount() == 0) {
                return new Result(Result.FAILED_CODE, "余票已无！");
            }
            Train train = new Train()
                    .setId(queryTrain.getId())
                    .setCount(queryTrain.getCount() - 1);
            trainDao.update(train);
        }
        return new Result(Result.SUCCESS_CODE, "购票成功！");
    }

    public void clearAll() {
        trainDao.deleteAll();
    }
}
